package com.ruoyi.sale.auditStatusMachine.impl;

import com.ruoyi.audit.domain.Audit;
import com.ruoyi.audit.domain.InventoryAmount;
import com.ruoyi.audit.mapper.AuditMapper;
import com.ruoyi.audit.mapper.InventoryAmountMapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.expressdelivery.service.ExpressDeliveryService;
import com.ruoyi.sale.auditStatusMachine.StatusService;
import com.ruoyi.sale.domain.SaleGoodsModel;
import com.ruoyi.sale.domain.SaleGoodsOrder;
import com.ruoyi.sale.domain.SaleorderModel;
import com.ruoyi.sale.mapper.SaleGoodsMapper;
import com.ruoyi.sale.mapper.SaleorderMapper;
import com.ruoyi.warehousing.domain.Warehousing;
import com.ruoyi.warehousing.domain.WarehousingRecords;
import com.ruoyi.warehousing.mapper.WarehousingMapper;
import com.ruoyi.warehousing.mapper.WarehousingRecordsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 销货单 通过
 * @Author Mr.Yi.Zhang
 * @Version 1.0
 */
@Component
public class Pass implements StatusService {

    private static final String FLAG = "1";
    @Override
    public String get() {
        return FLAG;
    }


    /** 销货单Mapper */
    private SaleGoodsMapper saleGoodsMapper;
    /** 销售审核Mapper */
    private AuditMapper auditMapper;
    /** 库存记录Mapper */
    private WarehousingMapper warehousingMapper;
    /** 库存操作记录Mapper */
    private WarehousingRecordsMapper warehousingRecordsMapper;
    /** 销售订单 **/
    private SaleorderMapper saleorderMapper;

    @Autowired
    ExpressDeliveryService expressDeliveryService;
    public Pass(
            SaleGoodsMapper saleGoodsMapper,
            AuditMapper auditMapper,
            WarehousingMapper warehousingMapper,
            WarehousingRecordsMapper warehousingRecordsMapper,
            SaleorderMapper saleorderMapper
    ) {
        this.saleGoodsMapper = saleGoodsMapper;
        this.auditMapper = auditMapper;
        this.warehousingMapper = warehousingMapper;
        this.warehousingRecordsMapper = warehousingRecordsMapper;
        this.saleorderMapper = saleorderMapper;
    }

    @Override
    public int execute(SaleGoodsOrder order) {
        // 同步销售审核状态
        Audit auditQueryParams = new Audit();
        auditQueryParams.setOrderType("3");// 销货单类型
        auditQueryParams.setOrderId(order.getSaleorderId());
        Audit audit = auditMapper.selectAuditByOrderId(auditQueryParams);
        audit.setAuditStatus(order.getSaleGoodsStatus());
        auditMapper.updateAudit(audit);

        // 同步库存
        // 封装查询参数
        HashMap<String, Object> saleGoodQueryParams = new HashMap<>();
        saleGoodQueryParams.put("saleGoodsId", order.getSaleorderId());
        // 获取当前销货单
        SaleGoodsOrder saleGoodsOrder = saleGoodsMapper.selectSaleGoodsById(saleGoodQueryParams);
        // 获取销货单内的产品
        List<SaleGoodsModel> saleGoodsModels = saleGoodsOrder.getSaleGoodsModels();
        // 库存数量操作
        if (!saleGoodQueryParams.isEmpty()) {
            WarehousingRecords warehousingRecords = new WarehousingRecords();
            for (SaleGoodsModel saleGoodsModel : saleGoodsModels) {
                int allnum = saleGoodsModel.getAllNum();
                //找库存表 获取id
                Warehousing warehousing = new Warehousing();
                warehousing.setDeptId(saleGoodsOrder.getDeptId());
                warehousing.setProductId(saleGoodsModel.getProductId());
                warehousing.setProductType(saleGoodsModel.getProductType());
                warehousing.setSelectId(saleGoodsModel.getProductId());
                warehousing.setBatch(saleGoodsModel.getBatch());
                Warehousing warehousing1 = warehousingMapper.selectWarehousing(warehousing);
                //存储本次减少的数量
                warehousingRecords.setInventoryNum(-saleGoodsModel.getNum());
                warehousingRecords.setAllnum(-allnum);

                //判断是否拥有该公司该产品该型号名称的库存记录
                if (warehousing1 == null) {
                    Long b = Long.valueOf(allnum);
                    warehousing.setAmount(b);
                    warehousingMapper.insertWarehousing(warehousing);
                } else {
                    Long warehousingNum = warehousing1.getAmount();
                    //int warehousingNum = warehousing1.getWarehousingNum();
                    Long num1 = warehousingNum - allnum;
                    warehousing.setAmount(num1);
                    warehousing.setWarehousingId(warehousing1.getWarehousingId());
                    if (num1 < 0) {
                        throw new RuntimeException("库存不足");
                    }
                    warehousingMapper.updateWarehousing(warehousing);
                }

                Long warehousingId = warehousing.getWarehousingId();
                warehousingRecords.setOrderNum(saleGoodsOrder.getSaleGoodsNum());
                warehousingRecords.setWarehousingId(warehousingId);
                warehousingRecords.setSupplierId(saleGoodsOrder.getCustomerId());
                warehousingRecords.setInventoryStatus("1");
                warehousingRecords.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
                warehousingRecordsMapper.insertWarehousingRecords(warehousingRecords);
            }
        }
        // 订单审核时间
        order.setAuditTime(new Date());
        // 同步销货单状态
        int result = saleGoodsMapper.auditSale(order);

        // 关闭创建销货单客户公司列表
        // 根据销售订单的订单号获取销售订单的订单ID
        String saleOrderId = saleorderMapper.querySaleOrderIdBySaleOrderNum(saleGoodsOrder.getWuliunumber());
        // 根据销售订单的订单ID获取销售订单中的产品列表
        List<SaleorderModel> saleOrderModels = saleorderMapper.selectSaleModelBySaleOrderId(saleOrderId);

        // 对销货单的出库列表中的数量进行分组
        Map<Long, List<SaleGoodsModel>> groupSaleGoodsModelBySaleOrderModelId = saleGoodsModels.stream()
                .collect(Collectors.groupingBy(SaleGoodsModel::getSaleorderModelId));
        // 计算销售订单的剩余未出库数量.已出库数量
        saleOrderModels.forEach(saleOrderModel -> {
            // 获取 销售单 对应的 销货单 中的 产品 出库数量？
            Long saleOrderModelId = saleOrderModel.getSaleorderModelId();
            List<SaleGoodsModel> models = groupSaleGoodsModelBySaleOrderModelId.get(saleOrderModelId);
            if (null != models && !models.isEmpty()) {
                int outNum = models.stream().map(SaleGoodsModel::getRemainingNum).filter(Objects::nonNull).mapToInt(Integer::intValue).sum();
                // 判断是否已出货
                if (0 == saleOrderModel.getRemainingNum()) {
                    throw new RuntimeException("该订单关联的销售订单已出库,本次重复操作!");
                }
                // 核验是否超出出库数量
                if (saleOrderModel.getRemainingNum() < outNum) {
                    throw new RuntimeException("销货订单中的出库数量超出销售订单发货数量!");
                }
                // 计算销售订单剩余出库数量
                saleOrderModel.setRemainingNum(saleOrderModel.getRemainingNum() - outNum);
                // 计算销售订单已出库数量
                saleOrderModel.setExecuteNum(saleOrderModel.getExecuteNum() + outNum);
            }
        });
        // 修改销售订单的出库列表的出库数量
        saleorderMapper.batchUpdateRemainingNumBySaleOrderModelId(saleOrderModels);

        // 同步库存记录
        Long deptId = SecurityUtils.getDeptId();
        List<InventoryAmount> collect = saleGoodsModels.stream().map(item -> {
            InventoryAmount ia = new InventoryAmount();
            ia.setDeptId(deptId);
            ia.setProductId(item.getProductId());
            ia.setProductType(item.getProductType());
            ia.setBatch(item.getBatch());
            return ia;
        }).collect(Collectors.toList());
        // inventoryAmountMapper.updateBatch(collect);

        return result;
    }

    @Autowired
    private InventoryAmountMapper inventoryAmountMapper;
}
